package com.corecmd.tcloud.tcim.ui.chatSessions;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.corecmd.tcloud.tcim.R;
import com.corecmd.tcloud.tcim.apis.ApiChatSessions;
import com.corecmd.tcloud.tcim.common.BaseViewHolder;
import com.corecmd.tcloud.tcim.common.Constant;
import com.corecmd.tcloud.tcim.common.RecyclerViewCommonAdapter;
import com.corecmd.tcloud.tcim.utils.AppUtil;
import com.corecmd.tcloud.tcim.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : tianshaojiao
 * @version : 1.0
 * @apiNote :
 * @date : 2021/3/2
 * @copyright :
 */
public class ChatSessionsFragment extends Fragment {
    RecyclerView recyclerView;
    private List<JSONObject> messages = new ArrayList<>();
    private RecyclerViewCommonAdapter adapter = null;
    SwipeRefreshLayout swipeRefreshLayout;
    private Handler messagesHandler = null;
    private static final int LOADMESSAGES = 1;
    private Context mcontext;
    private int currentMessagesPage = 1;
    private int messagesPageSize = 20;
    private int totalPage = 0;
    private  int lastVisibleItemPosition = 0;
    private boolean isLoadingMessages = false;
    private LinearLayoutManager layoutManager;
    private BroadcastReceiver broadcastReceiver;
    private boolean isPageHidden = false;
    private String mAppPackageName;
    public ChatSessionsFragment(){

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_chat_sessions,container,false);
        mcontext = this.getContext();
        mAppPackageName = AppUtil.getAppPackageName(mcontext);
        initHandler();
        initView(rootView);
        registerBroadcastReceiver();
        loadMessages(true);
        return rootView;
    }

    private void registerBroadcastReceiver() {
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Bundle dataBundle = intent.getExtras();
                if (null != dataBundle){
                    String receivedMsg = dataBundle.getString("messageContent");
                    System.out.println("会话界面收到一条消息："+receivedMsg);
                    //应用在前台时,判断当前Fragment状态是否为激活状态
                    if (AppUtil.isTopActivity(mcontext,mAppPackageName) && isPageHidden){
                        System.out.println("震动提示");
                    }
                }
            }
        };
        IntentFilter filter = new IntentFilter(Constant.IM_MESSAGE_BROADCAST_ACTION);
        mcontext.registerReceiver(broadcastReceiver, filter);
    }

    private void loadMessages(final boolean isRefresh) {
        isLoadingMessages  =  true;
        if (isRefresh){
            swipeRefreshLayout.setRefreshing(true);
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                String result = ApiChatSessions.listChatSessions(currentMessagesPage,messagesPageSize,"");
                JSONArray  jsonArrayAlbums = new JSONArray();
                int tmpTotalPage = 0;
                int tmpTotalRecord = 0;
                try {
                    if (null != result){
                        JSONObject jsonResult = JSONObject.parseObject(result);
                        if ("200".equals(jsonResult.getString("statusCode"))){
                            jsonArrayAlbums = jsonResult.getJSONArray("chatSessions");
                            tmpTotalPage = Integer.parseInt(jsonResult.getString("totalPage"));
                            tmpTotalRecord = Integer.parseInt(jsonResult.getString("totalRecord"));
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Message message = new Message();
                message.what = LOADMESSAGES;
                Bundle bundle = new Bundle();
                bundle.putString("messagesArray",jsonArrayAlbums.toJSONString());
                bundle.putInt("totalPage",tmpTotalPage);
                bundle.putInt("totalRecord",tmpTotalRecord);
                bundle.putBoolean("isRefresh",isRefresh);
                message.setData(bundle);
                messagesHandler.sendMessage(message);
            }
        }).start();
    }
    private void initView(View rootView) {
        recyclerView = (RecyclerView)rootView.findViewById(R.id.msgList_recyclerView);
        swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.SwipeRefreshLayout);
        swipeRefreshLayout.setColorSchemeResources(R.color.blueStatus);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                try {
                    currentMessagesPage = 1;
                    totalPage = 0;
                    messages.clear();
                    adapter.changeMoreStatus(RecyclerViewCommonAdapter.REFRESHING);
                    loadMessages(true);
                } catch (Exception e) {
                    Log.d("异常","刷新数据时异常:"+e.getMessage());
                }
            }
        });
        layoutManager = new LinearLayoutManager(rootView.getContext());
        recyclerView.setLayoutManager(layoutManager);
        adapter = new RecyclerViewCommonAdapter(rootView.getContext(),layoutManager,new ChatSessionViewHolderGenerator(),R.layout.chat_session_item,messages){
            @Override
            public void convert(final BaseViewHolder holder, Object data) {
                if (holder instanceof ChatSessionViewHolder){
                    ChatSessionViewHolder messageViewHolder = (ChatSessionViewHolder)holder;
                    messageViewHolder.bindView(data);
                    final OnItemClickListener onItemClickListener = getOnItemClickListener();
                    if (getOnItemClickListener() != null) {
                        messageViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                int position = holder.getLayoutPosition();
                                onItemClickListener.onItemClick(holder.itemView, position);
                            }
                        });

                        messageViewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                            @Override
                            public boolean onLongClick(View v) {
                                int position = holder.getLayoutPosition();
                                onItemClickListener.onItemLongClick(holder.itemView, position);
                                return false;
                            }
                        });
                    }
                }
            }
        };
        adapter.setOnItemClickListener(new RecyclerViewCommonAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                JSONObject itemInfo = (JSONObject)adapter.getItemInfo(position);
                Intent intent = new Intent();
                intent.setClass(mcontext,ChatSessionDetail.class);
                Bundle bundle = new Bundle();
                bundle.putString("chatSessionInfo",itemInfo.toJSONString());
                intent.putExtra("chatSessionInfo",bundle);
                startActivity(intent);
            }
            @Override
            public void onItemLongClick(View view, int position) {
                ToastUtil.showToaskShort(mcontext,"长按会话");
            }
        });
        recyclerView.setAdapter(adapter);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItemPosition + 1 == adapter.getItemCount()) {
                    boolean isRefreshing = swipeRefreshLayout.isRefreshing();
                    if (isRefreshing) {
                        return;
                    }
                    if (!isLoadingMessages) {
                        currentMessagesPage += 1;
                        //设置正在加载更多
                        adapter.changeMoreStatus(RecyclerViewCommonAdapter.LOADING_MORE);
                        loadMessages(false);
                    }
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
            }
        });
    }
    private void initHandler() {
        messagesHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(@NonNull Message msg) {
                swipeRefreshLayout.setRefreshing(false);
                if (msg.what == LOADMESSAGES){
                    isLoadingMessages  =  false;
                    try {
                        String dataArray = msg.getData().getString("messagesArray");
                        JSONArray data = (null != dataArray && !dataArray.isEmpty()) ? JSONObject.parseArray(dataArray):null;
                        boolean isRefresh = msg.getData().getBoolean("isRefresh");
                        List<JSONObject> newDatas = new ArrayList<>();
                        int loadStatusTips = RecyclerViewCommonAdapter.NO_LOAD_MORE;
                        if (data != null && data.size() > 0){
                            for (int i = 0; i < data.size(); i++){
                                newDatas.add(data.getJSONObject(i));
                            }
                            totalPage = msg.getData().getInt("totalPage");
                        }
                        if (currentMessagesPage < totalPage){
                            loadStatusTips = RecyclerViewCommonAdapter.PULLUP_LOAD_MORE;
                        }
                        if (isRefresh){
                            messages.clear();
                            adapter.notifyDataSetChanged();
                        }
                        messages.addAll(newDatas);
                        adapter.changeMoreStatus(loadStatusTips);
                    } catch (Exception e) {
                        Log.d("异常","更新视图异常:"+e.getMessage());
                    }
                }
                return false;
            }
        });
    }

    @Override
    public void onDestroyView() {
        if (null != broadcastReceiver){
            System.out.println("ChatSessionsFragment取消注册广播接收器");
            mcontext.unregisterReceiver(broadcastReceiver);
        }
        super.onDestroyView();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        isPageHidden = hidden;
        if (hidden){
            System.out.println("会话fragment隐藏");
        } else {
            System.out.println("会话fragment显示");
        }
    }
}
